<?php
namespace Home\Controller;
use Think\Controller;
use Common\Common\PurchaseLibrary;
use Common\Common\Sign_Model;

class IndexController extends Controller {


	public function createOrder(){

		$purchaseLibrary = new purchaseLibrary();


		//$purchaseLibrary->createOrder($userID, $channelId, $productKey, $productName, $shopType);
		$order_id = $purchaseLibrary->createOrder(16,'Coin_001','coin100',100);
		$array = array(
			'order_id' => $order_id,
			'type' => '1',
		);

		$result = json_encode($array);

		$this->show($result);

	}


	public function checkOrder(){



	}


	public function notify(){


		define('VERIFY_TOKEN', 'abc');
		$method = $_SERVER['REQUEST_METHOD'];
			
		// In PHP, dots and spaces in query parameter names are converted to
		// underscores automatically. So we need to check "hub_mode" instead
		//  of "hub.mode".
		if ($method == 'GET' && $_GET['hub_mode'] == 'subscribe' ) {
			echo $_GET['hub_challenge'];
			exit();
		} else if ($method == 'POST') {
			$updates = json_decode(file_get_contents("php://input"), true);
			// Replace with your own code here to handle the update
			// Note the request must complete within 15 seconds.
			// Otherwise Facebook server will consider it a timeout and
			// resend the push notification again.
			error_log('updates = ' . print_r($updates, true));
			$postData = $updates;
			
			// 访问日志 
			$str = $_POST;

			$str = "code_POST:".json_encode($postData)."\r\n";
			//$str .= "code_GET:".json_encode($_GET)."\r\n";
			//test save file

			$rose=fgets($bruce);
			$james=fopen("log.txt","a");
			fwrite($james,$str);
			fclose($james);

			$data = json_decode(json_encode($_GET),true);

			$app_secret = '';
			$itemsInfo = array();

			$app_secret = '5892d026fc445c71496f8bca4197f7df'; // 密钥

			$signModel = Sign_Model::getInstance();

			if (!array_key_exists('signed_request', $postData) or !array_key_exists('method', $postData)) {
				return;
			}

			$request = $signModel->parse_signed_request($postData['signed_request'], $app_secret);

			if (!$request) {
				//空数据
				return;
			}
			$response = '';
			$request_type = $postData['method'];

			if ($request_type == 'payments_get_items') {

				return;
			}
			if ($request_type == 'payments_status_update') {
				$orderDetails = $request['credits']['order_details'];
				$orderDetails = preg_replace('/"order_id":(\d+)/', '"order_id":"$1"', $orderDetails);
				$orderDetails = preg_replace('/"buyer":(\d+)/', '"buyer":"$1"', $orderDetails);
				$orderDetails = preg_replace('/"receiver":(\d+)/', '"receiver":"$1"', $orderDetails);
				$orderDetails = preg_replace('/"app":(\d+)/', '"app":"$1"', $orderDetails);
				$order_details = json_decode($orderDetails, true);
				$current_order_status = $order_details['status'];
				$order_id = $order_details['order_id'];
				if ($order_id != $postData['order_id']) {
					return;
				}
				$items = $order_details['items'];
				$item_id = $items[0]['item_id'];
				if (!array_key_exists($item_id, $itemsInfo)) {
					Log_Model::logToFile(__CLASS__ . __FUNCTION__ . '4', $item_id);
					return;
				}
				$itemInfo = $itemsInfo[$item_id];
				$itemCount = 1;
				$coin = $itemInfo['coin'] * $itemCount;

				$buyer = $order_details['buyer'];
				$receiver = $order_details['receiver']; //
				$time_placed = $order_details['time_placed'];
				$updata_time = array_key_exists('update_time', $order_details) ? $order_details['update_time'] : $time_placed;


				if ($current_order_status == 'placed') {
					$next_order_status = 'settled';

					// Construct response.
					$response = array(
                    'content' => array('status' => $next_order_status, 'order_id' => $order_id),
                    'method' => $request_type,
					);
					// Response must be JSON encoded.
					$response = json_encode($response);

					return;
				}
				if ($current_order_status == 'settled') {
					$orderLog = Facebooklog_Model::getOrderLog($order_id, $gameType, $current_order_status);

					// Construct response.
					$response = array(
                    'content' => array('status' => 'settled', 'order_id' => $order_id),
                    'method' => $request_type
					);
					// Response must be JSON encoded.
					$response = json_encode($response);
					if ($orderLog) {
						Registry::set('returnstr', $response);
						return;
					}
					Facebooklog_Model::addOrderLog($order_id, $gameType, $buyer, $receiver, $current_order_status, $itemCount, $item_id, $coin, $time_placed, $updata_time, $orderDetails);
					Server_Model::addCoin($gameType, $order_id, $buyer, $receiver, $current_order_status, $itemCount, $item_id, $coin, $time_placed, $updata_time, $orderDetails);
					Registry::set('returnstr', $response);
					return;
				}

				if ($current_order_status == 'disputed') {
					// 1. Track disputed item orders.
					// 2. Investigate user's dispute and resolve by settling or refunding the order.
					// 3. Update the order status asychronously using Graph API.
				} else if ($current_order_status == 'refunded') {
					Server_Model::addCoin($gameType, $order_id, $buyer, $receiver, $current_order_status, $itemCount, $item_id, $coin, $time_placed, $updata_time, $orderDetails);
				} else {
					$response = array(
                    'content' => array('status' => $current_order_status, 'order_id' => $order_id),
                    'method' => $request_type
					);
					// Response must be JSON encoded.
					$response = json_encode($response);
					Registry::set('returnstr', $response);
				}

			}





			echo json_encode($data);
			exit;
		}

	}


	public function login(){



	}
}